package com.wut.easyexcel.config;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.wut.easyexcel.common.BaseExcel;
import com.wut.easyexcel.utils.ExcelUtil.ExcelListener;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public abstract class AbstractDataListener<T> extends ExcelListener<T> {

    private final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    private final Validator beanValidator = factory.getValidator();

    @Override
    public void invoke(T data, AnalysisContext context) {
        super.invoke(data, context);
        BaseExcel excel = (BaseExcel) data;
        // 设置行数
        int rouNumber = context.readRowHolder().getRowIndex() + 1;
        excel.setRowNumber(rouNumber);

        Set<String> failedMassageSet = new HashSet<>();
        // Validate 校验数据
        Set<ConstraintViolation<Object>> violationSet = beanValidator.validate(data);
        if (!CollUtil.isEmpty(violationSet)) {
            failedMassageSet.addAll(violationSet.stream().map(ConstraintViolation::getMessage).collect(Collectors.toSet()));
        }

        validate(data, failedMassageSet);
        ((BaseExcel) data).setFailedMassageSet(failedMassageSet);

        if (CollUtil.isEmpty(((BaseExcel) data).getFailedMassageSet())) {
            processSuccessData(data);
        }
    }

    /**
     * 自定义校验数据
     */
    public abstract void validate(T data, Set<String> failedMassageSet);

    /**
     * 处理成功数据
     */
    public abstract void processSuccessData(T data);
}
